<template>
  <view class="phone-container">
    
    <!-- 操作按钮区域 -->
    <view class="btn-group">
      <button 
        class="add-btn" 
        @click="showAddForm = true"
        v-if="!showAddForm"
      >
        添加新号码
      </button>
      <button 
        class="cancel-btn" 
        @click="cancelAdd"
        v-if="showAddForm"
      >
        取消添加
      </button>
    </view>
    
    <!-- 新增号码表单（默认隐藏） -->
    <view class="add-form" v-if="showAddForm">
      <view class="form-item">
        <text class="form-label">电话号码：</text>
        <input 
          v-model="newPhone.phoneNumber" 
          type="number" 
          placeholder="请输入11位手机号"
          maxlength="11"
          class="form-input"
        />
        <text class="error-tip">{{ phoneError }}</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">归属地：</text>
        <input 
          v-model="newPhone.phoneAddress" 
          placeholder="例如：北京"
          class="form-input"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">服务商：</text>
        <input 
          v-model="newPhone.supplier" 
          placeholder="例如：联通"
          class="form-input"
        />
      </view>
      
      <button class="confirm-add-btn" @click="addNewPhone">确认添加</button>
    </view>
    
    <!-- 号码列表 -->
    <view class="phone-list">
      <view v-if="phoneList.length === 0 && !showAddForm" class="empty-tip">
        暂无电话号码，请添加
      </view>
      
      <view v-for="(item, index) in phoneList" :key="item.phoneId" class="phone-item">
        <view class="phone-info">
          <view class="phone-number">{{ item.phoneNumber }}</view>
          <view class="phone-detail">
            <text>归属地：{{ item.phoneAddress || '未知' }}</text>
            <text>服务商：{{ item.supplier || '未知' }}</text>
          </view>
        </view>
        
        <view class="phone-actions">
          <button 
            class="action-btn delete-btn" 
            @click="deletePhone(item.phoneId, index)"
          >
            删除
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { phoneApi } from '../../api/phoneApi';
import { onLoad } from '@dcloudio/uni-app';

export default {
  data() {
    return {
      phoneList: [],
      showAddForm: false, // 控制表单显示/隐藏
      newPhone: {
        userId: '',
        phoneNumber: '',
        phoneAddress: '',
        supplier: ''
      },
      phoneError: '' // 手机号验证错误提示
    };
  },
  
  onLoad() {
    // 获取当前用户ID
    const userInfo = uni.getStorageSync('userInfo');
    this.newPhone.userId = userInfo?.userId;
    // 加载电话列表
    this.loadPhoneList();
  },
  
  methods: {
    // 取消添加，重置表单
    cancelAdd() {
      this.showAddForm = false;
      this.phoneError = '';
      this.newPhone.phoneNumber = '';
      this.newPhone.phoneAddress = '';
      this.newPhone.supplier = '';
    },
    
    // 验证手机号
    validatePhone() {
      this.phoneError = '';
      const phone = this.newPhone.phoneNumber;
      if (!phone) {
        this.phoneError = '请输入电话号码';
        return false;
      }
      if (!/^1\d{10}$/.test(phone)) {
        this.phoneError = '请输入有效的11位手机号';
        return false;
      }
      return true;
    },
    
    // 加载电话列表
    async loadPhoneList() {
      try {
        uni.showLoading({ title: '加载中...' });
        const res = await phoneApi.getPhoneList(this.newPhone.userId);
        
        if (res.code === 0 && Array.isArray(res.data)) {
          this.phoneList = res.data;
        } else {
          uni.showToast({ title: '加载失败', icon: 'none' });
        }
      } catch (error) {
        console.error('加载电话列表失败:', error);
        uni.showToast({ title: error.message, icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 添加新号码
    async addNewPhone() {
      // 验证手机号
      if (!this.validatePhone()) {
        return;
      }
      
      try {
        uni.showLoading({ title: '添加中...' });
        const res = await phoneApi.addPhone(this.newPhone);
        
        if (res.code === 0) {
          uni.showToast({ title: '添加成功', icon: 'success' });
          this.cancelAdd(); // 重置表单并隐藏
          this.loadPhoneList(); // 重新加载列表
        } else {
          uni.showToast({ title: res.msg || '添加失败', icon: 'none' });
        }
      } catch (error) {
        console.error('添加号码失败:', error);
        uni.showToast({ title: error.message, icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 删除号码
    async deletePhone(phoneId, index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个号码吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              const result = await phoneApi.deletePhone(phoneId);
              
              if (result.code === 0) {
                uni.showToast({ title: '删除成功', icon: 'success' });
                this.phoneList.splice(index, 1);
              } else {
                uni.showToast({ title: result.msg || '删除失败', icon: 'none' });
              }
            } catch (error) {
              console.error('删除号码失败:', error);
              uni.showToast({ title: error.message, icon: 'none' });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.phone-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 36rpx;
  text-align: center;
  margin: 30rpx 0;
  font-weight: bold;
}

.btn-group {
  margin-bottom: 20rpx;
}

.add-btn {
  background-color: #007aff;
  color: white;
  width: 100%;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
  width: 100%;
  border: 1px solid #ddd;
}

/* 表单样式 */
.add-form {
  background-color: white;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 25rpx;
}

.form-label {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  color: #333;
}

.form-input {
  height: 70rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 15rpx;
  font-size: 28rpx;
}

.error-tip {
  color: #ff3b30;
  font-size: 24rpx;
  margin-top: 5rpx;
  height: 28rpx;
}

.confirm-add-btn {
  background-color: #007aff;
  color: white;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  margin-top: 10rpx;
}

/* 列表样式 */
.phone-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.phone-item {
  background-color: white;
  border-radius: 10rpx;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.phone-number {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.phone-detail {
  font-size: 26rpx;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 5rpx;
}

.phone-actions {
  display: flex;
  gap: 10rpx;
}

.action-btn {
  padding: 0 20rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 26rpx;
}

.delete-btn {
  background-color: #ff3b30;
  color: white;
}

.empty-tip {
  text-align: center;
  padding: 50rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>